package com.xunfang.portal.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xunfang.portal.model.entity.Book;
import com.xunfang.portal.model.request.SearchRequest;
import com.xunfang.portal.service.BookCollectionService;
import com.xunfang.portal.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/bookCollection")
@Tag(name = "收藏夹相关接口")
public class BookCollectionController {
    
    @Autowired
    private JwtUtils jwtUtil;
    
    @Autowired
    private BookCollectionService bookCollectionService;

    /**
    * 添加到收藏夹
    */
    @PostMapping("/{bookId}")
    public ResponseEntity<?> addToFavorites(
            @RequestHeader(
                name = "Authorization", required = false) String token,
                    @PathVariable("bookId") Long bookId) {
        //获取用户ID
        String userId = jwtUtil.getValue(token, "userId");
        bookCollectionService.addToFavorites(bookId, userId);
        return ResponseEntity.ok("收藏成功");
    }

    /**
     * 判断书籍是否已经收藏
     */
    @GetMapping("/checkFavorite/{bookId}")
    @Operation(summary = "判断书籍是否已经收藏")
    public ResponseEntity<Boolean> checkFavorite(
            @RequestHeader("Authorization") String token,
            @PathVariable("bookId") Long bookId) {

        //获取当前用户的userId
        String userId = jwtUtil.getValue(token, "userId");
        // 判断书籍是否已经收藏的逻辑
        Boolean isFavorite = bookCollectionService.checkFavorite(bookId, userId);
        return ResponseEntity.ok(isFavorite);
    }

    /**
     * 移除收藏
     */
    @DeleteMapping("/remove/{bookId}")
    @Operation(summary = "移除收藏")
    public ResponseEntity<?> removeToFavorite(
            @RequestHeader("Authorization") String token,
            @PathVariable Long bookId) {
        //获取当前用户的userId
        String userId = jwtUtil.getValue(token, "userId");
        // 判断书籍是否已经收藏的逻辑
        bookCollectionService.removeToFavorite(bookId,userId);
        return ResponseEntity.ok("取消收藏成功");
    }

    /**
     * 查询我的收藏
     *       /{currentPage}/{pageSize}
     *
     *      //注释  麻婆豆腐
     */
    @PostMapping("/myFavorites")
    @Operation(summary = "查询我的收藏")
    public ResponseEntity<Page<Book>> myFavorites(
            @RequestHeader("Authorization") String token,
            @RequestBody SearchRequest params) {
        //获取当前用户的userId
        String userId = jwtUtil.getValue(token, "userId");
        // 查询我的收藏的逻辑
        Page<Book> favorites = bookCollectionService
                .getMyFavorites(userId,
                        params.getPageNum(), params.getPageSize());
        return ResponseEntity.ok(favorites);
    }
}